﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CuaHangMayTinh.BusinessEntities;
using CuaHangMayTinh.BusinessLogicLayer;
using CuaHangMayTinh.PresentationLayer.Report;
using CuaHangMayTinh.Utilities;
using DevComponents.DotNetBar.Controls;
using Microsoft.VisualBasic;

namespace CuaHangMayTinh.PresentationLayer
{
    public partial class FormBanHang : Form
    {
        DoiSoSangChu sotienchu = new DoiSoSangChu(0);

        /// <summary>
        /// hiển thị list tên nhà cung cấp 
        /// </summary>
        private List<string> tenkhachhang = new List<string>();

        /// <summary>
        /// chứa thông tin của danh sách mặt hàng
        /// </summary>
        private DataTable dtmathang = MatHangManager.Find_All(false);

        /// <summary>
        /// tạo 1 datatable
        /// </summary>
        private DataTable table;

        /// <summary>
        /// danh sách model mặt hàng
        /// </summary>
        private List<ModelMatHangEntity> dsModelMatHangEntities = new List<ModelMatHangEntity>();

        /// <summary>
        /// danh sach chi tiết bán hàng entity
        /// </summary>
        private List<ChiTietBanHangEntity> dscChiTietBanHangEntities = new List<ChiTietBanHangEntity>();

        /// <summary>
        /// danh sách đơn vị tính
        /// </summary>
        private List<DonViTinhEntity> listDonViTinhEntities = DonViTinhManager.ConvertToList(DonViTinhManager.Find_All());

        /// <summary>
        /// tạo đối tượng lưu lít lọa mặt hàng
        /// </summary>
        private List<LoaiMatHangEntity> listLoaiMatHangentity =
            LoaiMatHangManager.ConvertToList(LoaiMatHangManager.Find_All());

        /// <summary>
        /// tạo đối tượng lưu trữ bán hàng
        /// </summary>
        private BanHangEntity banhangentity;

        /// <summary>
        /// tạo đối tượng lusu trữ khách hàng
        /// </summary>
        private KhachHangEntity khachHangEntity;

        /// <summary>
        /// tạo đối tượng lưu trữ nhân viên
        /// </summary>
        private NhanVienEntity nhanVienEntity;

        /// <summary>
        /// tạo đối tượng lưu trữ lỗi 
        /// </summary>
        private string Text = string.Empty;

        /// <summary>
        /// lưu số luơng
        /// </summary>
        private int SoLuong = 0;

        /// <summary>
        /// lưu giá trị tổng tiền
        /// </summary>
        private decimal TongTien = 0;
        /// <summary>
        /// form khởi tạo bánhangf
        /// </summary>
        public FormBanHang()
        {
            InitializeComponent();
        }

        public FormBanHang(NhanVienEntity nvEntity)
            : this()
        {
            nhanVienEntity = nvEntity;
        }

        /// <summary>
        /// phuwogn thức laod của form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormBanHang_Load(object sender, EventArgs e)
        {
            LoadForm();
        }

        private void LoadForm()
        {
            dsModelMatHangEntities = new List<ModelMatHangEntity>();
            //            DataTable dtmodelMathang =DataUtil.ChangeColumn(ModelMatHangManager.Find_All(false));
            DataTable dtmodelMathang = ModelMatHangManager.Find_All(false);
            comboBoxEx_modelmathang.DataSource = dtmodelMathang.AsEnumerable().Where(x => x.Field<int>("TinhTrang") != 0).CopyToDataTable();
            comboBoxEx_modelmathang.DisplayMember = "Model";
            //            comboBoxEx_modelmathang.DropDownColumns = "Model,Hãng sản xuất,Nước sản xuất,Bảo hành";
            comboBoxEx_modelmathang.DropDownColumns = "Model,HangSX,NuocSX,BaoHanh";
            comboBoxEx_modelmathang.DropDownWidth = 400;
            LoadNhanVienToCbb();
            table = CreateDatable();
            dateTimeInput_ngaylap.Value = DateTime.Now;
            Set_txtMaHD();
            dataGridViewX_Select.DataSource = null;
            label_soluong.Text = "0";
            label_tongtien.Text = "0";
            label_sotienchu.Text = "";
        }

        /// <summary>
        /// khi thay dổi cbb model mặt hàng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx_modelmathang_SelectedIndexChanged(object sender, EventArgs e)
        {
            ModelMatHangEntity rowmodelmh = getModelMatHangEntity((DataRowView)comboBoxEx_modelmathang.SelectedValue);
            int mamodel = rowmodelmh.MaModelMH;
            var dr = dtmathang.AsEnumerable().Where(x => x.Field<int>("MaModelMH") == mamodel && x.Field<int>("TinhTrang") == 0);
            DataTable table = new DataTable();
            if (dr.Any())
            {
                comboBoxEx_mathang.Enabled = true;
                table = dr.CopyToDataTable();
                comboBoxEx_mathang.DataSource = table;
                comboBoxEx_mathang.DisplayMember = "Serial_Code";
                buttonX_Them.Enabled = true;
            }
            else
            {
                comboBoxEx_mathang.Enabled = false;
                buttonX_Them.Enabled = false;
            }
        }

        /// <summary>
        /// load nhan vien lên combobox
        /// </summary>
        private void LoadNhanVienToCbb()
        {
            DataTable dt = DataUtil.ChangeColumn(KhachHangManager.Find_All());
            comboBoxEx_khachhang.DataSource = dt;
            comboBoxEx_khachhang.DisplayMember = "Tên khách hàng";
            comboBoxEx_khachhang.DropDownColumns = "Tên khách hàng,CMND-Mã số thuế,Số điện thoại,Địa chỉ";
            comboBoxEx_khachhang.DropDownWidth = 400;
            SetAutoCompleKhachHang(dt);
            EnableKhachHang(false);
        }

        /// <summary>
        /// tạo autocomple cho khách hàng
        /// </summary>
        /// <param name="dt"></param>
        private void SetAutoCompleKhachHang(DataTable dt)
        {
            if (dt != null)
            {
                foreach (DataRow row in dt.Rows)
                {
                    tenkhachhang.Add(row[1].ToString());
                }
            }
            textBoxX_ten.AutoCompleteCustomSource.AddRange(tenkhachhang.ToArray());
        }

        /// <summary>
        /// hiển thị hoặc khóa nhập khách hàng
        /// </summary>
        /// <param name="i"></param>
        private void EnableKhachHang(bool i)
        {
            textBoxX_cmnd.Enabled = i;
            textBoxX_diachi.Enabled = i;
            textBoxX_sodienthoai.Enabled = i;
        }

        /// <summary>
        /// bắt sự kiện thay đổi khách hàng
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxEx_khachhang_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxEx_khachhang.Text = "...";
            ComboBoxEx ex = sender as ComboBoxEx;
            DataRowView row = (DataRowView)ex.SelectedItem;
            khachHangEntity = KhachHangManager.ConvertToList(KhachHangManager.Find_ID((int)row[0]))[0];
            SetKhachHangEntity(row);
            EnableKhachHang(false);
        }

        /// <summary>
        /// lấy row chuyển lên form
        /// </summary>
        /// <param name="row"></param>
        private void SetKhachHangEntity(DataRow row)
        {
            textBoxX_ten.Text = row[1].ToString();
            textBoxX_cmnd.Text = row[2].ToString();
            textBoxX_diachi.Text = row[4].ToString();
            textBoxX_sodienthoai.Text = row[5].ToString();
        }

        /// <summary>
        /// lấy datarowview chuyển lên form
        /// </summary>
        /// <param name="row"></param>
        private void SetKhachHangEntity(DataRowView row)
        {
            textBoxX_ten.Text = row[1].ToString();
            textBoxX_cmnd.Text = row[2].ToString();
            textBoxX_diachi.Text = row[4].ToString();
            textBoxX_sodienthoai.Text = row[5].ToString();
        }

        /// <summary>
        /// tạo mới khách hàng entiy từ from
        /// </summary>
        /// <returns></returns>
        private KhachHangEntity getKhachHangEntity()
        {
            return new KhachHangEntity()
            {
                TenKH = textBoxX_ten.Text,
                CMND_MaSoThue = textBoxX_cmnd.Text,
                DiaChi = textBoxX_diachi.Text,
                SoDT = textBoxX_sodienthoai.Text,
            };
        }

        /// <summary>
        /// bắt sự kiện khi rời khởi textbox 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxX_ten_Leave(object sender, EventArgs e)
        {
            if (tenkhachhang.Contains(textBoxX_ten.Text))
            {
                DataTable dt = (DataTable)comboBoxEx_khachhang.DataSource;
                var results = dt.AsEnumerable();
                DataRow kq = results.FirstOrDefault(x => x.Field<string>("Tên khách hàng") == textBoxX_ten.Text);
                SetKhachHangEntity(kq);
                EnableKhachHang(false);
            }
            else
            {
                EnableKhachHang(true);
            }
        }

        /// <summary>
        /// tạo một datatable mới hiển thị thông tin dưới datagrid 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateDatable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Serial");
            dt.Columns.Add("ModelMatHang");
            dt.Columns.Add("HangSX");
            dt.Columns.Add("NuocSX");
            dt.Columns.Add("BaoHanh");
            dt.Columns.Add("CauHinh");
            dt.Columns.Add("GiaNhap");
            dt.Columns.Add("LoaiMatHang");
            dt.Columns.Add("DonVitinh");
            return dt;
        }

        /// <summary>
        /// trộn 2 database với nhau
        /// </summary>
        /// <param name="dt1"></param>
        /// <returns></returns>
        private DataTable ADDtable(DataTable dt1)
        {
            var dt2 = (DataTable)dataGridViewX_Select.DataSource;
            if (dt2 == null)
            {
                dt2 = table.Clone();
            }
            dt2.Merge(dt1);
            return dt2;
        }

        /// <summary>
        /// bắt sự kiện nút thêm
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX_Them_Click(object sender, EventArgs e)
        {
            DataTable dt = table.Clone();
            ModelMatHangEntity rowmodelmh = getModelMatHangEntity((DataRowView)comboBoxEx_modelmathang.SelectedValue);
            var rowmh = (DataRowView)comboBoxEx_mathang.SelectedValue;
            var gia = ModelMatHangManager.GetGia(rowmodelmh.MaModelMH);
            MatHangEntity matHang = getMatHangEntity(rowmh);
            rowmodelmh.ListMatHang.Add(matHang);
            dt.Rows.Add(new[]
            {
                rowmh[6],
                rowmodelmh.Model,
                rowmodelmh.HangSX,
                rowmodelmh.NuocSX,
                rowmodelmh.BaoHanh,
                rowmodelmh.CauHinh,
                gia,
                listLoaiMatHangentity.AsEnumerable()
                    .Where(x=>x.MaLoaiMH ==rowmodelmh.MaLoaiMH)
                    .Select(x=>x.TenLoaiMH).FirstOrDefault(),
                listDonViTinhEntities.AsEnumerable()
                    .Where(x => x.MaDonViTinh == rowmodelmh.MaDonViTinh)
                    .Select(x => x.DonVi)
                    .FirstOrDefault()
            });
            dataGridViewX_Select.DataSource = ADDtable(dt);
            var t = dtmathang.AsEnumerable().FirstOrDefault(x => x.Field<int>("MaMH") == matHang.MaMH);
            t["TinhTrang"] = 1;
            if (dsModelMatHangEntities.Any(x => x.MaModelMH == rowmodelmh.MaModelMH))
            {
                dsModelMatHangEntities.FirstOrDefault(x => x.MaModelMH == rowmodelmh.MaModelMH).ListMatHang.Add(matHang);
                dscChiTietBanHangEntities.FirstOrDefault(x => x.MaModelMH == rowmodelmh.MaModelMH).SoLuong++;
            }
            else
            {
                dsModelMatHangEntities.Add(rowmodelmh);
                var chitietbanhang = new ChiTietBanHangEntity(0, rowmodelmh.MaModelMH, 1, gia);
                dscChiTietBanHangEntities.Add(chitietbanhang);
            }
            SoLuong += 1;
            label_soluong.Text = SoLuong.ToString();
            TongTien += gia + gia * (decimal)0.1 + gia * ((decimal)doubleInput_loinhuan.Value / 100);
            label_tongtien.Text = TongTien + " Đồng";
            sotienchu.So = Convert.ToInt32(TongTien);
            label_sotienchu.Text = sotienchu.ToString();
            comboBoxEx_modelmathang_SelectedIndexChanged(null, null);
        }

        /// <summary>
        /// lấy modelmat hang từ datagirview row
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private ModelMatHangEntity getModelMatHangEntity(DataRowView row)
        {
            var entity = new ModelMatHangEntity()
            {
                MaModelMH = (int)row[0],
                MaLoaiMH = (int)row[1],
                Model = (string)row[2],
                HangSX = (string)row[3],
                NuocSX = (string)row[4],
                CauHinh = (string)row[5],
                BaoHanh = (int)row[6],
                SoLuong = (int)row[7],
                TinhTrang = (int)row[8],
                MaDonViTinh = (int)row[9]
            };
            return entity;
        }

        /// <summary>
        /// lấy mặt hàng entity từ datarowview 
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private MatHangEntity getMatHangEntity(DataRowView row)
        {
            MatHangEntity entity = new MatHangEntity()
            {
                MaMH = (int)row[0],
                MaModelMH = (int)row[1],
                MaHoaDonNhap = (int)row[2],
                MaHoaDonBan = 0,
                MaPhieuXuatKhoTraHang = 0,
                Serial_Code = (string)row[6],
                MaPhieuBaoHanhSuaChua = 0,
                TinhTrang = 0
            };
            return entity;
        }

        /// <summary>
        /// sự kiện click nút thanh toán
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX_thanhtoan_Click(object sender, EventArgs e)
        {
            if (dataGridViewX_Select.Rows.Count > 0)
            {
                if (khachHangEntity == null)
                {
                    khachHangEntity = getKhachHangEntity();
                    if (KhachHangManager.InsertGetID(khachHangEntity, ref Text) > 0)
                    {
                        MessageBox.Show(Text);
                        return;
                    }
                }
                banhangentity = new BanHangEntity(0, textBoxX_maphieunhap.Text, nhanVienEntity.MaNV, khachHangEntity.MaKH, dateTimeInput_ngaylap.Value, 10, (float)doubleInput_loinhuan.Value, TongTien, textBox_ghichu.Text);
                banhangentity.ListChiTiet = dscChiTietBanHangEntities;
                banhangentity.ListModel = dsModelMatHangEntities;
                int x = BanHangManager.InsertTS(banhangentity);
                if (x > 0)
                {
                    banhangentity.MaBanHang = x;
                    MessageBox.Show("Thanh toán thành công !");
                    buttonX_thanhtoan.Enabled = false;
                    buttonX_IN.Enabled = true;
                    buttonX_Them.Enabled = false;
                    buttonX_Xoa.Enabled = false;
                    toolStripBtn_taomoi.Enabled = true;
                    toolStripButton_Excel.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("Chưa có mặc hàng cần bán !");
            }
        }

        /// <summary>
        /// sự kiện click nút hủy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX_Xoa_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow selectrow in dataGridViewX_Select.SelectedRows)
            {
                var serial = selectrow.Cells[0].Value;
                foreach (var mathangentity in dsModelMatHangEntities)
                {
                    SoLuong -= mathangentity.ListMatHang.Where(x => x.Serial_Code == (string)serial).Count();
                    var t = dtmathang.AsEnumerable().FirstOrDefault(x => x.Field<string>("Serial_code") == serial);
                    t["TinhTrang"] = 0;
                    if (mathangentity.ListMatHang.Any(x => x.Serial_Code == (string)serial))
                    {
                        mathangentity.ListMatHang.RemoveAll(x => x.Serial_Code == (string)serial);
                        dataGridViewX_Select.Rows.Remove(dataGridViewX_Select.SelectedRows[0]);
                        decimal gia =
                            dscChiTietBanHangEntities.FirstOrDefault(x => x.MaModelMH == mathangentity.MaModelMH).GiaBan;
                        TongTien -= (gia + gia * (decimal)0.1 + gia * ((decimal)doubleInput_loinhuan.Value / 100));
                        if (mathangentity.ListMatHang.Count < 1)
                            dscChiTietBanHangEntities.RemoveAll(x => x.MaModelMH == mathangentity.MaModelMH);
                    }
                }
            }
            dsModelMatHangEntities.RemoveAll(x => x.ListMatHang.Count == 0);
            label_soluong.Text = SoLuong.ToString();
            label_tongtien.Text = TongTien + " Đồng";
            sotienchu.So = Convert.ToInt32(TongTien);
            label_sotienchu.Text = sotienchu.ToString();
            comboBoxEx_modelmathang_SelectedIndexChanged(null, null);
        }

        private void buttonX_IN_Click(object sender, EventArgs e)
        {
            FormReportHoaDon reportHoaDon = new FormReportHoaDon(banhangentity, nhanVienEntity, khachHangEntity, listDonViTinhEntities, true);
            reportHoaDon.ShowDialog();
        }

        void Set_txtMaHD()
        {
            DataTable dt;
            textBoxX_maphieunhap.Enabled = false;
            dt = BanHangManager.GetMaHDMax();
            string nam = DateTime.Now.Year.ToString().Substring(1, DateTime.Now.Year.ToString().Length - 1);
            if (dt.Rows.Count == 0)
            {
                textBoxX_maphieunhap.Text = nam + "-0000001";
                return;
            }
            string mahd = dt.Rows[0][0].ToString();
            string[] temp = mahd.Split('-');
            if (temp[0].CompareTo(nam) != 0)
            {
                textBoxX_maphieunhap.Text = nam + "-0000001";
                return;
            }
            int duoi = 0;
            string Duoi = "";
            if (temp[0].CompareTo(nam) == 0)
            {
                mahd = "";
                duoi = (int.Parse(temp[1]) + 1);
                if (duoi < 10)
                    Duoi = "-000000" + duoi;
                else
                    if (duoi < 100)
                        Duoi = "-00000" + duoi;
                    else
                        if (duoi < 1000)
                            Duoi = "-0000" + duoi;
                        else
                            if (duoi < 10000)
                                Duoi = "-000" + duoi;
                            else
                                if (duoi < 100000)
                                    Duoi = "-00" + duoi;
                mahd = temp[0] + Duoi;
                textBoxX_maphieunhap.Text = mahd;
            }
        }

        private void toolStripBtn_In_Click(object sender, EventArgs e)
        {
            buttonX_IN_Click(null, null);
        }

        private void toolStripBtn_taomoi_Click(object sender, EventArgs e)
        {
            LoadForm();
        }
    }
}
